package simplepwdkeeper;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.saas.google.GoogleAccountsService;
import org.netbeans.saas.RestResponse;

public class Vars {

    private static String Version = "Simple Pwd Keeper v0.01-00a";

    public static String getVersion() {
        return Version;
    }
    // Properties
    /*
     * DataFile
     */
    public static Properties prop = new Properties();
    public static String PropFileName = "Options.xml";

    public static void SaveProperties() {
        try {
            prop.storeToXML(new FileOutputStream(PropFileName, false), null);
        } catch (IOException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void LoadProperties() {
        try {
            Vars.prop.loadFromXML(new FileInputStream(PropFileName));
        } catch (IOException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static ArrayList<obj_Pwd> PwdList = new ArrayList<obj_Pwd>();

    public static void SavePwdList() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(
                    new OutputStreamWriter(
                    new FileOutputStream(prop.getProperty("DataFile")), "UTF-8"));
        } catch (IOException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            bw.write("PWD file. " + sdf.format(Calendar.getInstance().getTime()));
            bw.newLine();
            bw.write("=============================");
            bw.newLine();

            for (obj_Pwd pwd : PwdList) {
                bw.write(getHexString(pwd.Name));
                bw.newLine();

                bw.write("{");
                bw.newLine();
                for (Entry<String, String> es : pwd.hm.entrySet()) {
                    bw.write(getHexString(es.getKey()));
                    bw.newLine();
                    bw.write(getHexString(es.getValue()));
                    bw.newLine();
                }
                bw.write("}");
                bw.newLine();

//                Long l = Calendar.getInstance().getTimeInMillis();
//                bw.write(l.toString());
//                bw.newLine();

                bw.write("=============================");
                bw.newLine();
            }
        } catch (IOException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            bw.close();
        } catch (IOException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void LoadPwdList() {
        BufferedReader br = null;
        String line = "";

        try {
            br = new BufferedReader(
                    new InputStreamReader(
                    new FileInputStream(prop.getProperty("DataFile")), "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (br == null) {
            return;
        }

        PwdList.clear();
        try {
            line = br.readLine();
            line = br.readLine();

            while ((line = br.readLine()) != null) {
                if (line.equals("=============================")) {
                    continue;
                }
                String name = getStringFromHex(line);
                line = br.readLine();
                HashMap<String, String> hm = new HashMap<String, String>();
                while (!(line = br.readLine()).equals("}")) {
                    hm.put(getStringFromHex(line), getStringFromHex(br.readLine()));
                }
                PwdList.add(new obj_Pwd(name, hm));
            }

        } catch (IOException ex) {
            Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
        }

//        Long l = new Long(0);
//        line = br.readLine();
//        l = Long.valueOf(line);
//        cs = new GregorianCalendar();
//        cs.setTimeInMillis(l);

        try {
            br.close();
        } catch (IOException ex) {
        }
    }

    public static String getHexString(String str) {
        String hexstr = "";
        int i = 0;
        while (i < str.length()) {
            Integer ic = str.codePointAt(i);
            hexstr = hexstr + Integer.toHexString(ic);
            hexstr = hexstr + "|";
            i++;
        }
        return hexstr;
    }

    public static String getStringFromHex(String hexstr) {
        if (hexstr == null) {
            return "";
        }
        String str = "";
        String s = "";
        Integer ci = 0;
        char c = (char) 0;
        int i = 0;
        while (i < hexstr.length()) {
            if (!hexstr.substring(i, i + 1).equals("|")) {
                s = s + hexstr.substring(i, i + 1);
                i++;
            } else {
                try {
                    ci = Integer.parseInt(s, 16);
                } catch (NumberFormatException ex) {
                    Logger.getLogger(Vars.class.getName()).log(Level.SEVERE, null, ex);
                    return "Error parsing HEX";
                }
                c = (char) ci.intValue();
                str = str + c;
                s = "";
                i++;
            }
        }
        return str;
    }

    public static void gtest() {
        try {
            String accountType = "type";
            String email = "my@email";
            String passwd = "mypassword";
            String service = "service";
            String source = null;

            RestResponse result = GoogleAccountsService.accountsClientLogin(accountType, email, passwd, service, source);
            System.out.println("The SaasService returned: " + result.getDataAsString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
